package com.study.webapp.leetcode;

/**
 * 二进制求和
 */
public class Leet_67 {

	public static void main(String[] args) {
		System.out.println(addBinary("1","111"));
	}



	public static String addBinary(String a, String b) {
		if (a == null || a.length() == 0) {
			return b;
		}
		if (b == null || b.length() == 0) {
			return a;
		}
		if ("0".equals(a) && "0".equals(b)) {
			return "0";
		}
		int len = Math.max(a.length(),b.length());
		if (len > a.length()) {
			StringBuilder aBuilder = new StringBuilder();
			for (int i = 0;i<len - a.length(); i++) {
				aBuilder.append("0");
			}
			aBuilder.append(a);
			a = aBuilder.toString();
		}
		if (len > b.length()) {
			StringBuilder bBuilder = new StringBuilder();
			for (int i = 0;i<len - b.length(); i++) {
				bBuilder.append("0");
			}
			bBuilder.append(b);
			b = bBuilder.toString();
		}


		StringBuilder builder = new StringBuilder();
		int pre = 0;
		for (int i = len-1;i>=0;i--) {
			Integer aPre = a.charAt(i) - '0';
			Integer bPre = b.charAt(i) - '0';
			Integer sum = aPre+bPre+pre;
			builder.append(sum % 2);
			pre = sum / 2;
		}
		if (pre > 0) {
			builder.append("1");
		}
		return builder.reverse().toString();

	}





}
